package com.jwgf.common;

import android.util.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class ZipUtils {
    // 压缩
    public static String compressToBase64(String str) throws IOException {
        if (str == null || str.length() == 0) {
            return str;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        gzip.write(str.getBytes());
        gzip.close();
        byte[] compressed = out.toByteArray();
        out.close();
        String result = Base64.encodeToString(compressed, Base64.DEFAULT);
        return result;
    }

    // 压缩
    public static String compressToBase64(byte[] str) throws IOException {
        if (str == null || str.length == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        gzip.write(str);
        gzip.close();
        byte[] compressed = out.toByteArray();
        out.close();
        String result = Base64.encodeToString(compressed, Base64.DEFAULT);
        return result;
    }

    // 解压缩
    public static byte[] uncompressFromBase64(String str) throws IOException {
        if (str == null || str.length() == 0) {
            return null;
        }
        byte[] compressed = Base64.decode(str, Base64.DEFAULT);
        ByteArrayInputStream in = new ByteArrayInputStream(compressed);
        GZIPInputStream gzip = new GZIPInputStream(in);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[256];
        int n;
        while ((n = gzip.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        // toString()使用平台默认编码，也可以显式的指定如toString("GBK")
        return out.toByteArray();
    }
}
